<template>
  <el-dialog
    v-bind="$attrs"
    :title="$t('page.import')"
    :width="step === 0 ? '70%' : '550px'"
    @open="handleOpen"
    @close="handleClose"
    @closed="() => (step = 0)"
  >
    <el-card
      style="border: 0px"
      shadow="never"
      :show-flag="cardPageShowFlag"
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="total"
      :current-page="pageNo"
      @current-change="currentChangeHandle"
    >
      <div v-show="step === 0">
        <el-form @submit.prevent.native inline class="p-4">
          <el-form-item>
            <el-input
              v-model="appNameOrPkgName"
              maxlength="255"
              :placeholder="$t('common.app_or_pkg_name')"
              @blur="() => (appNameOrPkgName = appNameOrPkgName.trim())"
              @keyup.enter.native="chooseAppPage"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="w-8"
              @click="chooseAppPage"
            >
              <svg-icon icon-class="search" />
            </el-button>
          </el-form-item>
        </el-form>
        <el-row class="flex flex-wrap" :gutter="20">
          <el-col
            v-for="item in list"
            :key="item.id"
            :lg="8"
            :md="12"
            class="mb-3"
          >
            <el-card
              :class="getAppClass(item)"
              @click.native="() => selectApp(item)"
            >
              <!-- TODO:require问题 -->
              <!-- <img
                :src="getImgUrl(item.iconUrl) || require('@/assets/images/default-icon.png')"
                alt
                width='60'
                height='60'
                class='mr-10'
                @error="() => item.iconUrl = require('@/assets/images/default-icon.png')"
              > -->
              <img
                :src="getImgUrl(item.iconUrl)"
                alt
                width="60"
                height="60"
                class="mr-10"
              />
              <div class="float-right ellipsis max-w-150px w-150px">
                <p style="line-height: 20px" class="ellipsis">
                  {{ item.appName }}
                </p>
                <p style="line-height: 20px" class="ellipsis">
                  {{ item.appPackageName }}
                </p>
                <p style="line-height: 20px" class="ellipsis">
                  {{ item.versionName }}
                </p>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8" />
        </el-row>
      </div>
      <!-- step 2 -->
      <div v-show="step === 1">
        <div class="flex justify-center m-auto pl-8 mb-2">
          <div class="flex items-center">
            <!-- <img
              :src="
                getImgUrl(currentApp.iconUrl, currentApp.os) ||
                require('@/assets/images/default-icon.png')
              "
              alt
              width="60"
              height="60"
              class="mr-10"
            /> -->
            <img
              :src="getImgUrl(currentApp.iconUrl, currentApp.os)"
              alt
              width="60"
              height="60"
              class="mr-10"
            />
            <div class="float-right">
              <p style="line-height: 30px">{{ currentApp.appName }}</p>
              <p style="line-height: 30px">{{ currentApp.appPackageName }}</p>
              <el-form
                @submit.prevent.native
                ref="selectApp"
                :model="appForm"
                :rules="rules"
              >
                <el-form-item prop="currentVersion">
                  <el-select
                    v-model="appForm.currentVersion"
                    size="mini"
                    placeholder="Version"
                  >
                    <el-option
                      v-for="item in versions"
                      :key="item.versionName"
                      :label="item.versionName"
                      :value="item.versionName"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <!--        <div class='text-center'>-->
        <!--          <el-button type='primary' @click='backToApp'>{{ $t('common.prev') }}</el-button>-->
        <!--          <el-button type='primary' :loading='loading' @click='pushApp'>{{ $t('page.confirm')}}</el-button>-->
        <!--        </div>-->
      </div>
    </el-card>
    <template #footer>
      <span v-if="step === 1" class="dialog-footer">
        <el-button text @click="handleClose">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="pushApp"
          >{{ $t('page.confirm') }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getAppVersionList, getAppPage } from '@/api/app'
import { addBatchDeviceByApp } from '@/api/batch'
import { getIcon } from '@/utils'
import { getAppInfoPage, queryAllSysApp } from '@/api/sysapp'

export default {
  inheritAttrs: false,
  props: { batchId: String },
  data() {
    return {
      cardPageShowFlag: 'AUTO_HIDE',
      step: 0,
      total: 0,
      currentApp: {},
      appNameOrPkgName: '',
      list: [],
      versions: [],
      pageNo: 1,
      pageSize: 9,
      pushSuccess: false,
      appForm: {
        currentVersion: ''
      },
      loading: false,
      rules: {
        currentVersion: [
          {
            required: true,
            message: 'Please select version',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted() {},
  methods: {
    handleOpen() {
      this.cardPageShowFlag = 'AUTO_HIDE'
      this.appNameOrPkgName = ''
      this.pageNo = 1
      this.chooseAppPage()
    },
    handleClose() {
      this.appForm.currentVersion = ''
      // this.cardPageShowFlag = 'AUTO_HIDE'
      this.$emit('update:model-value', false)
      this.appNameOrPkgName = ''
    },
    selectApp(app) {
      if (!this.isSupport(app)) {
        return
      }
      this.currentApp = app
      this.step = 1
      this.cardPageShowFlag = 'HIDE'
      this.versionsList()
    },
    getAppClass(app) {
      if (this.isSupport(app)) {
        return 'flex justify-center cursor-pointer w-full'
      } else {
        return 'flex justify-center cursor-not-allow w-full'
      }
    },
    isSupport(app) {
      return true
    },
    chooseAppPage() {
      queryAllSysApp({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        appName: this.appNameOrPkgName,
        filterGrayFlag: true
      }).then((res) => {
        this.list = res.data
        this.total = res.rows
      })
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.chooseAppPage()
    },
    currentChangeHandle(val) {
      this.pageNo = val
      this.chooseAppPage()
    },
    versionsList() {
      getAppInfoPage({
        packageName: this.currentApp.appPackageName,
        versionStyle: 1,
        pageSize: 100,
        pageNo: 1
      }).then((res) => {
        this.versions = res.data
        this.appForm.currentVersion = this.versions[0].versionName
      })
    },
    pushApp() {
      this.$refs['selectApp'].validate((valid) => {
        if (valid) {
          this.loading = true
          addBatchDeviceByApp(this.batchId, {
            pkgName: this.currentApp.appPackageName,
            versionName: this.appForm.currentVersion
          })
            .then(() => {
              this.$message.success(this.$t('batch.tip_app_add_success'))
              this.$emit('refreshDataList')
              this.handleClose()
              this.loading = false
            })
            .catch((e) => {
              if (e != null && e.code === '2030') {
                this.$message.warning(this.$t('batch.tip_app_add_empty'))
              } else {
                this.$confirmError(e)
              }
              this.loading = false
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    backToApp() {
      this.step = 0
      this.appForm.currentVersion = ''
      this.cardPageShowFlag = 'AUTO_HIDE'
    },
    getImgUrl(url, os) {
      if (url || os) {
        return getIcon(url, os)
      }
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .el-dialog .el-dialog__body {
  padding: 0;
}
.cursor-not-allow {
  cursor: not-allowed;
  border: 1px solid #dcdfe6;
  background: #dcdfe6;
}
</style>
